package com.ljl;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.json.JSONUtil;
import com.ljl.domain.NodeData;
import com.ljl.service.NodeDataService;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘家良
 * @date 2022/10/26 23:11
 * @description
 */
public class Gateway {

    public static void main(String[] args) {
        //配置网关程序的接口地址
        NodeDataService dataService = new NodeDataService("http://127.0.0.1:7001/upload");
        NodeData nodeData1 = new NodeData("东区食堂温湿度采集器", "东区三楼食堂", IdUtil.fastUUID());
        NodeData nodeData2 = new NodeData("西区食堂温湿度采集器", "西区一楼食堂", IdUtil.fastUUID());
        NodeData nodeData3 = new NodeData("图书馆温湿度采集器", "图书馆3楼", IdUtil.fastUUID());
        NodeData nodeData4 = new NodeData("北区创新楼温湿度采集器", "北区创新楼501", IdUtil.fastUUID());
        List<NodeData> source = new ArrayList<>();
        source.add(nodeData1);
        source.add(nodeData2);
        source.add(nodeData3);
        source.add(nodeData4);
        ThreadUtil.execute(() -> {
            while (true) {
                NodeData nodeData = randomGenerateNode(source);
                System.out.printf("生成节点数据[%s]\r\n", JSONUtil.toJsonStr(nodeData));
                dataService.recordData(nodeData);
                ThreadUtil.sleep(800, TimeUnit.MILLISECONDS);
            }
        });

    }

    /**
     * 从节点数据源中挑选节点数据，同时生成温度和湿度
     * @param list  数据源
     * @return 节点数据
     */
    public static NodeData randomGenerateNode(List<NodeData> list) {
        //从数据源里，随机抽选节点
        int size = list.size();
        int randomIndex = RandomUtil.randomInt(0, size);
        NodeData nodeData = list.get(randomIndex).clone();
        //随机生成温度和湿度
        float temperature = RandomUtil.randomBigDecimal(BigDecimal.ZERO, BigDecimal.valueOf(60)).floatValue();
        float humidity = RandomUtil.randomBigDecimal(BigDecimal.valueOf(40), BigDecimal.valueOf(60)).floatValue();
        nodeData.setTemperature(temperature);
        nodeData.setHumidity(humidity);
        //设置采集时间
        nodeData.setSampleTime(System.currentTimeMillis());
        return nodeData;
    }

}
